package com.hengpeng.itfints.controller.member;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.NotifyRequestMsg;
import com.hengpeng.itfinbase.message.partner.NotifyResponseMsg;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.PayRequestMsg;
import com.hengpeng.itfinbase.message.partner.PayResponseMsg;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfints.constants.TSConstants;
import com.hengpeng.itfints.controller.BaseController;


@Controller
public class PaymentController extends BaseController
{
	private String commPayBgNotifyUrlPrefix = "payment/commPayBgNotify";

	private String commPayPgNotifyUrlPrefix = "payment/commPayPgNotify";
	
	/**
	 * <pre>
	 * 充值
	 * </pre>
	 * @param request
	 * @param money
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/member_operate/imprest", method = RequestMethod.POST)
	@ResponseBody
	public ServiceResult<ResponseMessage> imprest(HttpServletRequest request, String money) throws Exception
	{
		ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
		if(serviceFactory.getCommonService().isTrustPattern()){
			PayRequestMsg reqMsg = new PayRequestMsg();
			UserInfo m = getSessionMember(request).getUser();
			reqMsg.setUserId(m.getId());
			reqMsg.setTransAmt(money);
			reqMsg.setPartnerTransType(PartnerTransType.NetSave);
			reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
			reqMsg.setBgRetUrl(service_notify_url);
	        reqMsg.setRetUrl(page_return_url);
			ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
			result.setReturnValue(response);
		}else{
			String providerId=request.getParameter("providerId");
			String defaultbank=request.getParameter("defaultbank");
			result=commPayRequestBody(request, providerId, money, defaultbank);
		}
		return result;
	}

	/**
	 * 银行充值请求
	 * @param request
	 * @param map
	 * @param providerId 支付商ID
	 * @param payMoney 支付金额
	 * @return
	 */
	public ServiceResult<ResponseMessage> commPayRequestBody(HttpServletRequest request, String providerId,
			String payMoney, String defaultbank)
	{
		ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
		String requestHtml = "";
		if (validateObjectsNullOrEmpty(providerId, payMoney))
		{
			requestHtml = "参数不能为空";
			result.setIsSuccess(false);
			result.setCode(RespCodeConstants.CommonCode.DATA_NOT_VALIDATA);
		}
		else
		{
			UserInfo m = getSessionMember(request).getUser();
			/*ServiceResult<PayResponseMsg> resultVali = validateMemberInfo(getBetCardNo(request), null);
			if (!resultVali.getIsSuccess())
			{
				return resultVali;
			}*/
			PayRequestMsg payRequest = new PayRequestMsg();
			payRequest.setProviderId(providerId);
			payRequest.setTransAmt(payMoney);
			payRequest.setUserId(m.getId());
			payRequest.setUserIp(getIpAddr(request));
			payRequest.setUserAgent(request.getHeader("user-agent"));
			payRequest.setRetUrl(getBasePath(request) + commPayPgNotifyUrlPrefix + providerId
					+ TSConstants.CLIENT_ACTION_SUFFIX);
			payRequest.setBgRetUrl(getBasePath(request) + commPayBgNotifyUrlPrefix + providerId
					+ TSConstants.CLIENT_ACTION_SUFFIX);
			
			//支付宝专用
			Object token = request.getSession().getAttribute(TSConstants.CLIENT_SESSION_ALIPAY_TOKEN);
			if (token != null && !token.toString().trim().equals(""))
			{
				payRequest.getOtherParams().put(TSConstants.CLIENT_SESSION_ALIPAY_TOKEN, token.toString());
			}
			if (defaultbank != null && !defaultbank.toString().trim().equals(""))
			{
				payRequest.getOtherParams().put("defaultbank", defaultbank.toString());
			}
			payRequest.setPartnerTransType(PartnerTransType.NetSave);
			payRequest.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
			payRequest.setBgRetUrl(service_notify_url);
			payRequest.setRetUrl(page_return_url);
			if(providerId.equals("2119")){
				payRequest.getOtherParams().put("WxPaytype", "NATIVE");  //微信支付额外配置
			}
			PayResponseMsg payResponse = (PayResponseMsg) serviceFactory.getProtFactory().remoteTrans(payRequest);
			if (!validateObjectsNullOrEmpty(payResponse))
			{
				if (payResponse.getRespCode().equalsIgnoreCase(RespCodeConstants.CommonCode.TRANS_SUC))
				{
					// requestHtml = payResponse.getOrderFormContent();
					result.setReturnValue(payResponse);
					result.setIsSuccess(true);
				}
				else
				{
					requestHtml = payResponse.getRespDesc();
					result.setMessage(requestHtml);
					result.setIsSuccess(false);
					result.setCode(payResponse.getRespCode());
				}
			}
			else
			{

				requestHtml = "请求出错，请重试！";
				result.setMessage(requestHtml);
				result.setIsSuccess(false);
				result.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
				logger.info("充值请求出错，返回null");
			}
		}
		return result;
	}
	
	/**
	 * <pre>
	 * 银行支付页面端返回
	 * </pre>
	 * @param map
	 * @param request
	 * @param response
	 * @param providerId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/payment/commPayPgNotify{providerId}")
	public String commPayPgNotify(ModelMap map, HttpServletRequest request, HttpServletResponse response,
			@PathVariable String providerId) throws Exception
	{
		if (providerId == null)
		{
			return returnErrorPage(map, "非法请求！");
		}
		NotifyRequestMsg requestMessage = new NotifyRequestMsg();
		requestMessage.setTransType(TransCodeConstants.PartnerTransCode.NOTIFY);
		//设置访问哪个接口
		Map<String, String> parameterMap = new HashMap<String, String>();
		parameterMap.put("RespType", "NetSave");
		requestMessage.setParameter(parameterMap);
		
		requestMessage.setIsBgNotify(false);
		StringBuffer parameter = new StringBuffer();
		Enumeration<String> params = request.getParameterNames();
		while (params.hasMoreElements())
		{
			String paramName = params.nextElement();
			parameter.append("&" + paramName + "=" + request.getParameter(paramName));
		}
		if (parameter.length() > 0)
		{
			parameter.delete(0, 1);
		}
		requestMessage.setParamString(parameter.toString());
		requestMessage.setProviderId(providerId);
		logger.info("commPayPgNotify充值{" + providerId + "}页面通知。通知参数{" + parameter.toString() + "}");
		NotifyResponseMsg port_result = (NotifyResponseMsg) serviceFactory.getProtFactory().remoteTrans(
				requestMessage);
		refreshSessionMember(request);
		map.put("resultObj", port_result);
		/*/memberCenter/index.htm*/
		return "redirect:/memberCenter/index.htm";
	}

	/**
	 * <pre>
	 * 银行支付后台端返回
	 * </pre>
	 * @param map
	 * @param request
	 * @param response
	 * @param providerId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/payment/commPayBgNotify{providerId}")
	public String commPayBgNotify(ModelMap map, HttpServletRequest request, HttpServletResponse response,
			@PathVariable String providerId) throws Exception
	{
		if (providerId == null)
		{
			return returnErrorPage(map, "非法请求！");
		}
		NotifyRequestMsg requestMessage = new NotifyRequestMsg();
		requestMessage.setIsBgNotify(true);
		requestMessage.setTransType(TransCodeConstants.PartnerTransCode.NOTIFY);
		//设置访问哪个接口
		Map<String, String> parameterMap = new HashMap<String, String>();
		parameterMap.put("RespType", "NetSave");
		requestMessage.setParameter(parameterMap);
		
		StringBuffer parameter = new StringBuffer();
		Enumeration<String> params = request.getParameterNames();
		while (params.hasMoreElements())
		{
			String paramName = params.nextElement();
			parameter.append("&" + paramName + "=" + request.getParameter(paramName));
		}
		if (parameter.length() > 0)
		{
			parameter.delete(0, 1);
		}
		requestMessage.setParamString(parameter.toString());
		//NetSave
		requestMessage.setProviderId(providerId);
		logger.info("commPayBgNotify充值{" + providerId + "}服务器通知。通知参数{" + parameter.toString() + "}");
		NotifyResponseMsg port_result = (NotifyResponseMsg) serviceFactory.getProtFactory().remoteTrans(
				requestMessage);
		refreshSessionMember(request);
		map.put("payPgNotifyUrl", getBasePath(request) + commPayPgNotifyUrlPrefix + providerId
				+ TSConstants.CLIENT_ACTION_SUFFIX);
		map.put("payBgNotifyUrl", getBasePath(request) + commPayBgNotifyUrlPrefix + providerId
				+ TSConstants.CLIENT_ACTION_SUFFIX);
		if (port_result.getRespCode().equalsIgnoreCase(Constant.TRANSACTION_RESPONSE_CODE_SUCCESS))
			return "/page/memberinfo/money/serviceNotify/notify" + providerId + ".jsp";
		else
			return "/page/memberinfo/money/payment_error.jsp";
	}
}
